require "Item"
BagTableFunc={}
BagTable={}
BagTableFunc.__index=BagTableFunc
setmetatable(BagTable, BagTableFunc)

BagTableFunc.create = function(self, tableBK, target, action, flag)
  local bagtable = {}
  bagtable.target = target
  bagtable.action = action
  setmetatable(bagtable, BagTableFunc)
  local items = CCArray:create()
  for i=1,12 do
    local item = CCBReader:load("BagItem.ccbi") 
    item:setContentSize(CCSizeMake(430,100))
    items:addObject(item)
  end
  local size = tableBK:getContentSize()
  local tableview = CCTableView:create(1, CCSizeMake(size.width, size.height-20), items)
  --print("ZhuangBeiLayer3.initBagTable", tableview)
  local x, y = ActionUtil.leftBottomPoint(tableBK)
  tableview:setPosition(x, y+10)
  --tableBK:getParent():addChild(tableview)
  bagtable.bagItems = items
  bagtable.bk = tableBK
  bagtable.node = tableview
  bagtable.table = tableview
  bagtable:setLockBK()
  
  bagtable.bagFlag = flag
  bagtable:updateEquipsExt()
  --if flag==nil or flag==0 then
  --  bagtable:updateEquipsAndItems()
  --elseif flag==1 then
  --  bagtable:updateEquips()
  --elseif flag==2 then
  --  bagtable:updateItems()
  --end
  
  if BagTable.tableOffset~=nil then
    TypeCast(tableview, "CCScrollView"):setContentOffset(BagTable.tableOffset)
  end
  return bagtable
end
BagTableFunc.setLockBK = function(self, enable)
  local bagSpaceTotal = 10 + UserData.userinfo.host.storageBoost
  for i=1,self.bagItems:count() do
    local item = self.bagItems:objectAtIndex(i-1)
    item = TypeCast(item, "CCLayer")
    for j=1,4 do
      local count = (12-i)*4+j
      if count > bagSpaceTotal then
        local button = CCButton:createWithFileName("onAddBagSpace", "lockbk.png", "lockbk.png", "lockbk.png", "")
        print("BagTableFunc.setLockBK", item, 1000+j)
        button:setPosition(item:getChildByTag(1000+j):getPosition())
        item:addChild(button)
        button:setTag(count)
        setObjectExtTable(button, self)
      end
    end
  end 
end
BagTableFunc.setEnable = function(self, enable)
  self.node:setTouchEnabled(enable)
  if self.buttonsInBag~=nil then
    for i=0,self.buttonsInBag:size()-1 do
      self.buttonsInBag:at(i):setTouchEnabled(enable)
    end 
  end
end
BagTableFunc.updateEquips = function(self)
  --[[
  if self.buttonsInBag~=nil then
    for k, v in pairs(self.buttonsInBag) do
      if v~=nil then
        v:getParent():removeChild(v,true)
      end
    end
  end
  ]]
  local equipIDs = UserData.userinfo.host.equips
  local sortedItems = {}
  for k,v in pairs(equipIDs) do
    if v.p >= 0 then
      sortedItems[#sortedItems+1] = {index=k, v=v}
    end
    --print()
  end
  print("BagTableFunc.updateEquips", #sortedItems) 
  local sortFunc = function(a, b) 
    local aa = Equip:create(tonumber(a.index))
    local bb = Equip:create(tonumber(b.index))
    local sa = string.format("%d%s", aa.equipConfig.level, aa.equipConfig.name)
    local sb = string.format("%d%s", bb.equipConfig.level, bb.equipConfig.name)
    print(sa, "---", sb)
    return sa>sb 
  end
  table.sort(sortedItems, sortFunc)
  for k,v in pairs(equipIDs) do
      local c = #self.buttonsInBag
      if v.p >= 0 then
        local index = math.floor(c/4)
        local index1 = c%4
        local item = self.bagItems:objectAtIndex(self.bagItems:count()-index-1)
        item = TypeCast(item, "CCLayer")
        local einfo = UserData.config.models.Equip[v.e]
        local imgName = nameFromPath(einfo.asset)
        local button = CCButton:createWithFileName(self.action, imgName, imgName, imgName, "")
        setObjectExtTable(button, self.target)
        button:setTag(k)
        local bkSP = item:getChildByTag(1001+index1)
        button:setPosition(bkSP:getPosition())
        item:addChild(button)
        self.buttonsInBag[#self.buttonsInBag+1]=button
      end
    end
end
BagTableFunc.updateItems = function(self)
  print("BagTableFunc.updateItems")
  --[[if self.buttonsInBag~=nil then
    for k, v in pairs(self.buttonsInBag) do
      if v~=nil then
        v:getParent():removeChild(v,true)
      end
    end
  end
  ]]
  --self.buttonsInBag = {} 
  local items = UserData.userinfo.host.items
  local sortedItems = {}
  for k,v in pairs(items) do
    sortedItems[#sortedItems+1] = {index=k, v=v}
    --print()
  end
  print("BagTableFunc.updateItems", #sortedItems) 
  local sortFunc = function(a, b) 
    local aa = Item:createWithId(tonumber(a.v.i))
    local bb = Item:createWithId(tonumber(b.v.i))
    local sa = string.format("%s%s", aa.itemConfig.alias, aa.itemConfig.name)
    local sb = string.format("%s%s", bb.itemConfig.alias, bb.itemConfig.name)
    print(sa, "---", sb)
    return sa>sb 
  end
  table.sort(sortedItems, sortFunc)
  print("BagTableFunc.updateItems sorted", #sortedItems) 
  for k,v in ipairs(sortedItems) do
    local c = #self.buttonsInBag
    local index = math.floor(tonumber(c)/4)
    local index1 = tonumber(c)%4
    local bagitem = Item:createWithIndex(tonumber(v.index))
    local itemLayer = bagitem:createItemLayer(self.action, self.target)
    local bkLayer = self.bagItems:objectAtIndex(self.bagItems:count()-index-1)
    bkLayer = TypeCast(bkLayer, "CCLayer")
    print("##", c, v.index, bagitem.itemConfig.name)
    local bkSP = bkLayer:getChildByTag(1001+index1)
    itemLayer:setPosition(bkSP:getPosition())
    bkLayer:addChild(itemLayer)
    self.buttonsInBag[#self.buttonsInBag+1]=itemLayer
  end
end

BagTableFunc.updateEquipsExt = function(self)
  if self.buttonsInBag~=nil then
    for k, v in pairs(self.buttonsInBag) do
      if v~=nil then
        v:getParent():removeChild(v,true)
      end
    end
  end

  self.buttonsInBag = {} 
  if self.bagFlag==1 then
    self:updateEquips()
    self:updateItems()
  elseif self.bagFlag==2 then
    self:updateItems()
    self:updateEquips()
  end
end

BagTableFunc.updateEquipsAndItems = function(self)
  if self.buttonsInBag~=nil then
    for i=0,self.buttonsInBag:size()-1 do
      local b = self.buttonsInBag:at(i)
      if b~=nil then
        b:getParent():removeChild(b,true)
      end
    end
  end
  self.buttonsInBag = Array:create()
  local equipIDs = UserData.userinfo.host.equips

  for k,v in pairs(equipIDs) do
    if v.p >= 0 then
      local index = math.floor(v.p/4)
      local index1 = v.p%4
      --print("ZhuangBeiLayer3.showEquipInTable", k, v, index,index1)
      local item = self.bagItems:objectAtIndex(self.bagItems:count()-index-1)
      item = TypeCast(item, "CCLayer")
      local einfo = UserData.config.models.Equip[v.e]
      local imgName = nameFromPath(einfo.asset)
      local button = CCButton:createWithFileName(self.action, imgName, imgName, imgName, "")
      setObjectExtTable(button, self.target)
      button:setTag(k)
      local bkSP = item:getChildByTag(1001+index1)
      button:setPosition(bkSP:getPosition())
      item:addChild(button)
      self.buttonsInBag:append(button)
    end
  end

  local items = UserData.userinfo.host.items
  for k,v in pairs(items) do
    --print("BagTableFunc.updateEquips", k, v)
    --local itemLayer = CCLayer:create()
    local index = math.floor(tonumber(k)/4)
    local index1 = tonumber(k)%4
    local bagitem = Item:createWithIndex(tonumber(k))
   
    local itemLayer = bagitem:createItemLayer(self.action, self.target)
    local bkLayer = self.bagItems:objectAtIndex(self.bagItems:count()-index-1)
    bkLayer = TypeCast(bkLayer, "CCLayer")
    print("##", k, bagitem.itemConfig.name)
    --[[
    local imgName = nameFromPath(bagitem.itemConfig.asset)
    --local button = CCSprite:create(imgName)
    local button = CCButton:createWithFileName(self.action, imgName, imgName, imgName, "")
    setObjectExtTable(button, self.target)
    button:setTag(100000+tonumber(k))
    itemLayer:addChild(button)
    local lb = CCLabelTTF:create(string.format("%d", bagitem.itemInfo.n), "Helvetica", 28)
    itemLayer:addChild(lb)
    lb:setPosition(ccp(25, -25))]]
    local bkSP = bkLayer:getChildByTag(1001+index1)
    itemLayer:setPosition(bkSP:getPosition())
    bkLayer:addChild(itemLayer)
    self.buttonsInBag:append(itemLayer)
  end
end
BagTableFunc.updateEquipsAndItemsExt = function(self)
  if self.buttonsInBag~=nil then
    for i=0,self.buttonsInBag:size()-1 do
      local b = self.buttonsInBag:at(i)
      if b~=nil then
        b:getParent():removeChild(b,true)
      end
    end
  end
  self.buttonsInBag = Array:create()
  local equipIDs = UserData.userinfo.host.equips

  for k,v in pairs(equipIDs) do
    if v.p >= 0 then
      local index = math.floor(v.p/4)
      local index1 = v.p%4
      local item = self.bagItems:objectAtIndex(self.bagItems:count()-index-1)
      item = TypeCast(item, "CCLayer")
      local einfo = UserData.config.models.Equip[v.e]
      local imgName = nameFromPath(einfo.asset)
      local button = CCButton:createWithFileName(self.action, imgName, imgName, imgName, "")
      setObjectExtTable(button, self.target)
      button:setTag(k)
      local bkSP = item:getChildByTag(1001+index1)
      button:setPosition(bkSP:getPosition())
      item:addChild(button)
      self.buttonsInBag:append(button)
    end
  end

  local items = UserData.userinfo.host.items
  for k,v in pairs(items) do
    local index = math.floor(tonumber(k)/4)
    local index1 = tonumber(k)%4
    local bagitem = Item:createWithIndex(tonumber(k))
   
    local itemLayer = bagitem:createItemLayer(self.action, self.target)
    local bkLayer = self.bagItems:objectAtIndex(self.bagItems:count()-index-1)
    bkLayer = TypeCast(bkLayer, "CCLayer")
    print("##", k, bagitem.itemConfig.name)
    local bkSP = bkLayer:getChildByTag(1001+index1)
    itemLayer:setPosition(bkSP:getPosition())
    bkLayer:addChild(itemLayer)
    self.buttonsInBag:append(itemLayer)
  end
end

BagTableFunc.onAddBagSpace = function(self, node, event)
  --local index = node:getTag()-10
  local index = UserData.userinfo.host.storageBoost+1
  self.openCount = index

  local coin = UserData.config.models.BagSpace[index].coin
  local friends = UserData.config.models.BagSpace[index].friends
  local cash = UserData.config.models.BagSpace[index].friends
  print("BagTableFunc.onAddBagSpace", index, coin, friends, cash)

  self.dlg = {}
  self.dlg.node = CCBReader:load("OpenBagDialog.ccbi")
  TypeCast(self.dlg.node:getChildByTag(1011), "CCLabelTTF"):setString(string.format("花费军饷：%d", coin))
  TypeCast(self.dlg.node:getChildByTag(1012), "CCLabelTTF"):setString(string.format("%d好友+%d现金", friends, cash))
  setObjectExtTable(self.dlg.node:getChildByTag(1020), self)
  setObjectExtTable(self.dlg.node:getChildByTag(1021), self)
  setObjectExtTable(self.dlg.node:getChildByTag(1111), self)

  MainScene.scene:removeChild(ZhuangBeiScene.instance.node, true)
  MainScene.scene:addChild(self.dlg.node)
end
BagTableFunc.onAddBagSpaceCoinButton = function(self, node, event)
  NetworkRequest.bagOpen("true", self.openCount, "onOpenBagComplete", self)
  --setTouchEnabledAll(self.dlg.node, false)
  LoadScene:showLoadingScene()
end
BagTableFunc.onAddBagSpaceFriendButton = function(self, node, event)
  NetworkRequest.bagOpen("false", self.openCount, "onOpenBagComplete", self)
  --setTouchEnabledAll(self.dlg.node, false)
  LoadScene:showLoadingScene()
end
BagTableFunc.onCloseButton = function(self, node, event)
  if self.dlg~=nil then
    MainScene.scene:removeChild(self.dlg.node, true)
  end
  MainScene.scene:addChild(ZhuangBeiScene.getNode().node)
end
BagTableFunc.onOpenBagComplete = function(self, data)
  LoadScene:removeLoadingScene()
  local res = cjson.decode(data)
  if res.ret==0 then
    NetworkRequest.syncData(res)
  else
    showMessage(res.msg, ccc3(255,255,0))
  end
  if self.dlg~=nil then
    MainScene.scene:removeChild(self.dlg.node, true)
  end
  MainScene.scene:addChild(ZhuangBeiScene.getNode().node)
end
--BagTableFunc.show = function(self, visible)
--  self.tableview:setVisible(visible)
--end
